package com.itemp.ms66scan;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.google.zxing.integration.android.IntentIntegrator;
import com.journeyapps.barcodescanner.CaptureActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private final static String TAG = "yu_MS66Scan";
    private Button scanButton;
    private BluetoothSocket bluetoothSocket;
    BluetoothAdapter bluetoothAdapter;
    boolean stopDiscover;
    private String CONNECT_BLUETOOTH_MAC = "22:22:FD:0F:09:00";//"22:22:56:3A:00:00";
    private EditText editText;
    private Button sendButton;
    private OutputStream outputStream;
    private MyThread myThread;
    private BluetoothDevice btDevice;
    private String UUIDs =  "00001101-0000-1000-8000-00805F9B34FB";
    private String wifiSSID;
    private String wifiPassword;

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @SuppressLint({"MissingInflatedId", "MissingPermission"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        scanButton = findViewById(R.id.scan_button);
        scanButton.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
            startActivityForResult(intent, 0);
        });
        editText = findViewById(R.id.edit_text);
        sendButton = findViewById(R.id.send);
        sendButton.setOnClickListener(view -> {
            String sendText = wifiSSID + ";" +  editText.getText().toString().trim() + ";";
            Log.d(TAG, "sendText = " + sendText);
            if (outputStream != null) {
                try {
                    outputStream.write(sendText.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        requestPermission();
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

        findViewById(R.id.connect_button).setOnClickListener(view -> {
            if (bluetoothAdapter != null) {
                if (!bluetoothAdapter.isEnabled()) {
                    bluetoothAdapter.enable();
                }
                bluetoothAdapter.startDiscovery();
                stopDiscover = false;
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);
        if (bluetoothAdapter != null) {
            if (!bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.enable();
            }
            bluetoothAdapter.startDiscovery();
        }

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if(wifiInfo != null){
            String tempString = wifiInfo.getSSID();
            wifiSSID = tempString.substring(1,tempString.length() -1);
            Log.d(TAG, "wifiSSID: "  + wifiSSID);
        }
    }

    private void connectBTServer() {
        if (myThread != null) {
            myThread.interrupt();
            myThread = null;
        }
        myThread = new MyThread();
        myThread.start();
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                if (bluetoothAdapter != null) {
                    BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(CONNECT_BLUETOOTH_MAC);
                    if (bluetoothDevice != null) {
                        bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(UUIDs));
                        bluetoothAdapter.cancelDiscovery();
                        bluetoothSocket.connect();
                        outputStream = bluetoothSocket.getOutputStream();
                        String message = wifiSSID + ";";
                        if (outputStream != null) {
                            outputStream.write(message.getBytes());
                        }
                    }
                }
            } catch (SecurityException e) {
                Log.d(TAG, "" + e.toString());
            } catch (IOException e) {
                Log.d(TAG, "" + e.toString());
                try {
                    if (bluetoothSocket != null) {
                        bluetoothSocket.close();
                    }
                } catch (IOException ex) {
                    Log.d(TAG, "" + e.toString());
                }
            }
        }
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                @SuppressLint("MissingPermission")
                String deviceName = btDevice.getName();
                String deviceAddress = btDevice.getAddress();
                Log.d(TAG, "找到设备：" + deviceName + " [" + deviceAddress + "]");
                if (CONNECT_BLUETOOTH_MAC.equals(deviceAddress)) {
                    stopDiscover = true;
                    connectBTServer();
                }
            }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                Log.d(TAG, "ACTION_DISCOVERY_STARTED");
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Log.d(TAG, "ACTION_DISCOVERY_FINISHED");
                if (!stopDiscover && bluetoothAdapter != null) {
                    bluetoothAdapter.startDiscovery();
                }
            }
        }
    };

    public void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            ArrayList<String> permissionsList = new ArrayList<>();
            String[] permissions = {
                    Manifest.permission.CAMERA,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.CHANGE_WIFI_STATE,
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
            };
            for (String perm : permissions) {
                if (PackageManager.PERMISSION_GRANTED != checkSelfPermission(perm)) {
                    permissionsList.add(perm);
                }
            }
            if (!permissionsList.isEmpty()) {
                String[] strings = new String[permissionsList.size()];
                requestPermissions(permissionsList.toArray(strings), 0);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0 && resultCode == RESULT_OK) {
            String result = data.getStringExtra("SCAN_RESULT");
            Log.d(TAG, "result = " + result);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (bluetoothSocket != null) {
                bluetoothSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        stopDiscover = false;
        if (myThread != null) {
            myThread.interrupt();
            myThread = null;
        }
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}